import { Injectable,NotFoundException ,BadRequestException} from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Exam, ExamDocument } from '../schemas/exams/exam.schema';
import { Question, QuestionDocument } from '../schemas/questions/question.schema';
import { ExamRecord, ExamRecordDocument } from '../schemas/exam-records/exam-record.schema';
import {QuestionGroup, QuestionGroupDocument, } from '../schemas/question-group/question-group.schema';
import { Types } from 'mongoose';
import * as fs from 'fs';
import * as path from 'path';

@Injectable()
export class ExamsService {
  constructor(
    @InjectModel(Exam.name) private examModel: Model<ExamDocument>,
    @InjectModel(Question.name) private questionModel: Model<QuestionDocument>,
    @InjectModel(ExamRecord.name) private recordModel: Model<ExamRecordDocument>,
    @InjectModel(QuestionGroup.name) private questionGroupModel: Model<QuestionGroupDocument>
  ) {}


  async findAll(): Promise<Exam[]> {
    return this.examModel.find().exec();}

  // 创建考卷（支持分块）
  async createExam(createExamDto:any): Promise<Exam> {
    return this.examModel.create({
      title: createExamDto.title,
      type: createExamDto.type,
      detailType: createExamDto.detailType,
      sections: createExamDto.sections.map(section => ({
        name: section.name,
        subType: section.subType,
        duration: section.duration,
        minDuration: section.minDuration || 0,
        questions: [],
        questionGroups: []
       
      })),
    });
  }

 

  // 提交考卷（分块计分）
  async submitExam(
    userId: string,
    examId: string,
    answers: Record<string, number | number[]>
  ) {
    const exam = await this.examModel.findById(examId)
      .populate<{ sections: Array<{ questions: QuestionDocument[] }> }>({
        path: 'sections.questions',
        model: 'Question',
      })
      .exec();
  
    if (!exam) throw new Error('Exam not found');
  
    let totalScore = 0;
    const answerMap: Record<string, { userAnswer: any; correctAnswer: any }> = {};
  
    // 遍历所有分块的题目
    exam.sections.forEach((section, sectionIndex) => {
      section.questions.forEach(question => {
        const answerKey = `${sectionIndex}-${question._id}`;
        const userAnswer = answers[answerKey];
        let isCorrect = false;
  
        // 根据题目类型验证答案（修改类型比较逻辑）
        switch (question.type) {
          case 'single':
            // 将数字答案转换为字符串进行比较
            isCorrect = String(userAnswer) === question.correctAnswer[0];
            break;
          case 'multiple':
            if (Array.isArray(userAnswer)){
              // 将数字数组转换为字符串数组进行比较
              const userAnswerStrings = userAnswer.map(String);
              isCorrect = userAnswerStrings.sort().toString() === question.correctAnswer.sort().toString();
            }
            break;
          case 'judge':
            // 将布尔值转换为字符串进行比较
            isCorrect = String(userAnswer) === question.correctAnswer[0];
            break;
        }
  
        if (isCorrect) totalScore += question.score;
        answerMap[answerKey] = { userAnswer, correctAnswer: question.correctAnswer };
      });
    });
  
    return this.recordModel.create({ userId, examId, answers: answerMap, totalScore });
  }



// 删除考卷
async remove(id: string): Promise<Exam> {
  return await this.examModel.findByIdAndDelete(id);
}

// 通过 type 获取考卷
async findByType(type?: string, detailType?: string, subType?: string): Promise<Exam[]> {
  const query: any = {};

  // 动态添加type条件
  if (type !== undefined) {
    query.type = type;
  }

  // 动态添加detailType条件
  if (detailType !== undefined) {
    query.detailType = detailType;
  }

  // 动态添加subType条件，使用elemMatch匹配数组元素
  if (subType !== undefined) {
    query.sections = {
      $elemMatch: {
        subType: subType,
      },
    };
  }

  return this.examModel.find(query);
}



// src/exams/exams.service.ts
async getQuestionDetail(questionId: string) {
  // 先尝试查找大题组
  const group = await this.questionGroupModel.findOne({
    questionIds: new Types.ObjectId(questionId)
  }).populate('materialId');

  if (group) {
    // 属于材料题组的小题
    const question = await this.questionModel.findById(questionId);
    return {
      type: 'material',
      material: group.materialId,
      question,
      groupId: group._id
    };
  }

  // 独立小题
  const question = await this.questionModel.findById(questionId);
  return { 
    type: 'single',
    question 
  };
}
// ... 现有代码 ...

// 添加单独题目到考卷分块
async addQuestionToSection(examId: string, sectionIndex: number, questionId: string) {
  const exam = await this.examModel.findById(examId);
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }

  if (sectionIndex >= exam.sections.length) {
    throw new BadRequestException(`分块索引 ${sectionIndex} 超出范围`);
  }

  const question = await this.questionModel.findById(questionId);
  if (!question) {
    throw new NotFoundException('题目不存在');
  }

  const section = exam.sections[sectionIndex];
  
  // 避免重复添加题目
  if (!section.questions) {
    section.questions = [];
  }
  
  if (!section.questions.includes(questionId)) {
    section.questions.push(questionId);
    await exam.save();
  }
  
  return exam;
}

// 添加题目组到考卷分块
async addQuestionGroupToSection(examId: string, sectionIndex: number, groupId: string) {
  const exam = await this.examModel.findById(examId);
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }

  if (sectionIndex >= exam.sections.length) {
    throw new BadRequestException(`分块索引 ${sectionIndex} 超出范围`);
  }

  const questionGroup = await this.questionGroupModel.findById(groupId);
  if (!questionGroup) {
    throw new NotFoundException('题目组不存在');
  }

  const section = exam.sections[sectionIndex];
  
  // 初始化 questionGroups 数组（如果不存在）
  if (!section.questionGroups) {
    section.questionGroups = [];
  }
  
  // 避免重复添加题目组
  if (!section.questionGroups.includes(groupId)) {
    section.questionGroups.push(groupId);
    await exam.save();
  }
  
  return exam;
}

// 从考卷分块中移除单独题目
async removeQuestionFromSection(examId: string, sectionIndex: number, questionId: string) {
  const exam = await this.examModel.findById(examId);
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }

  if (sectionIndex >= exam.sections.length) {
    throw new BadRequestException(`分块索引 ${sectionIndex} 超出范围`);
  }

  const section = exam.sections[sectionIndex];
  
  if (section.questions) {
    const index = section.questions.indexOf(questionId);
    if (index !== -1) {
      section.questions.splice(index, 1);
      await exam.save();
    }
  }
  
  return exam;
}

// 从考卷分块中移除题目组
async removeQuestionGroupFromSection(examId: string, sectionIndex: number, groupId: string) {
  const exam = await this.examModel.findById(examId);
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }

  if (sectionIndex >= exam.sections.length) {
    throw new BadRequestException(`分块索引 ${sectionIndex} 超出范围`);
  }

  const section = exam.sections[sectionIndex];
  
  if (section.questionGroups) {
    const index = section.questionGroups.indexOf(groupId);
    if (index !== -1) {
      section.questionGroups.splice(index, 1);
      await exam.save();
    }
  }
  
  return exam;
}

// 获取考卷详情（填充分块中的题目和题目组）
async getExamDetail(examId: string) {
  const exam = await this.examModel.findById(examId).exec();
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }

  // 处理每个分块
  const populatedSections = await Promise.all(exam.sections.map(async (section) => {
    // 获取分块中的所有题目
    const questions = await this.questionModel.find({
      _id: { $in: section.questions || [] }
    }).exec();

    // 获取分块中的所有题目组
    const questionGroups = await this.questionGroupModel.find({
      _id: { $in: section.questionGroups || [] }
    }).populate('questions').exec();

    return {
      ...section.toObject(),
      questions: questions,
      questionGroups: questionGroups
    };
  }));

  return {
    ...exam.toObject(),
    sections: populatedSections
  };
}

// 添加新的分块到考卷
async addSection(examId: string, sectionData: {
  name: string;
  subType: string;
  duration: number;
  minDuration?: number;
}): Promise<Exam> {
  const exam = await this.examModel.findById(examId);
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }
  
  // 创建新分块
  const newSection = {
    name: sectionData.name,
    subType: sectionData.subType,
    duration: sectionData.duration,
    minDuration: sectionData.minDuration || 0,
    questions: [],
    questionGroups: []
  };
  
  // 添加到考卷
  exam.sections.push(newSection);
  return exam.save();
}

// 删除考卷中的分块
async removeSection(examId: string, sectionIndex: number): Promise<Exam> {
  const exam = await this.examModel.findById(examId);
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }
  
  if (sectionIndex < 0 || sectionIndex >= exam.sections.length) {
    throw new BadRequestException(`分块索引 ${sectionIndex} 超出范围`);
  }
  
  // 删除指定索引的分块
  exam.sections.splice(sectionIndex, 1);
  return exam.save();
}

// 修改考卷中的分块
async updateSection(
  examId: string, 
  sectionIndex: number, 
  updateData: {
    name?: string;
    subType?: string;
    duration?: number;
    minDuration?: number;
  }
): Promise<Exam> {
  const exam = await this.examModel.findById(examId);
  if (!exam) {
    throw new NotFoundException('考卷不存在');
  }
  
  if (sectionIndex < 0 || sectionIndex >= exam.sections.length) {
    throw new BadRequestException(`分块索引 ${sectionIndex} 超出范围`);
  }
  
  // 更新分块数据
  const section = exam.sections[sectionIndex];
  if (updateData.name !== undefined) section.name = updateData.name;
  if (updateData.subType !== undefined) section.subType = updateData.subType;
  if (updateData.duration !== undefined) section.duration = updateData.duration;
  if (updateData.minDuration !== undefined) section.minDuration = updateData.minDuration;
  
  return exam.save();
}
}